1. Count Capital Letters in a String
# Method 1: Using isupper()
string = input("Enter a string: ")
capital_count = 0
for char in string:
if char.isupper():
capital_count += 1
print(f"Number of capital letters: {capital_count}")
# Method 2: Using ASCII values
string = input("Enter a string: ")
capital_count = 0
for char in string:
if 'A' <= char <= 'Z':
capital_count += 1
print(f"Number of capital letters: {capital_count}")
Sample Output:
Enter a string: Hello World PYTHON Number of capital letters: 8
2. Count Total Number of Vowels
# Method 1: Case insensitive
string = input("Enter a string: ")
vowel_count = 0
vowels = "aeiouAEIOU"
for char in string:
if char in vowels:
vowel_count += 1
print(f"Number of vowels: {vowel_count}")
# Method 2: Case insensitive using lower()
string = input("Enter a string: ")
vowel_count = 0
vowels = "aeiou"
for char in string.lower():
if char in vowels:
vowel_count += 1
print(f"Number of vowels: {vowel_count}")
# Method 3: Count individual vowels
string = input("Enter a string: ")
vowels = "aeiou"
vowel_counts = {vowel: 0 for vowel in vowels}
for char in string.lower():
if char in vowels:
vowel_counts[char] += 1
print("Vowel counts:")
for vowel, count in vowel_counts.items():
print(f"{vowel}: {count}")
print(f"Total vowels: {sum(vowel_counts.values())}")
Sample Output:
Enter a string: Programming is Fun Number of vowels: 5
3. Print Words in Separate Lines
# Method 1: Using split()
sentence = input("Enter a sentence: ")
words = sentence.split()
print("Words in separate lines:")
for word in words:
print(word)
# Method 2: Manual splitting
sentence = input("Enter a sentence: ")
word = ""
print("Words in separate lines:")
for char in sentence:
if char != ' ':
word += char
else:
if word:
print(word)
word = ""
# Print the last word
if word:
print(word)
Sample Output:
Enter a sentence: This is a sample sentence Words in separate lines: This is a sample sentence
4. Count Substring Occurrences
# Method 1: Using count() method
string = input("Enter the main string: ")
substring = input("Enter the substring: ")
count = string.count(substring)
print(f"The substring occurs {count} times")
# Method 2: Manual traversal (left to right)
string = input("Enter the main string: ")
substring = input("Enter the substring: ")
count = 0
sub_len = len(substring)
for i in range(len(string) - sub_len + 1):
if string[i:i+sub_len] == substring:
count += 1
print(f"The substring occurs {count} times")
# Method 3: Using find() method
string = input("Enter the main string: ")
substring = input("Enter the substring: ")
count = 0
pos = 0
while True:
pos = string.find(substring, pos)
if pos == -1:
break
count += 1
pos += 1 # Move one position forward for overlapping substrings
print(f"The substring occurs {count} times")
Sample Output:
Enter the main string: ABCDCDC Enter the substring: CDC The substring occurs 2 times
5. Count Alphabet Occurrences (Case Insensitive)
# Method 1: Using dictionary
string = input("Enter a string: ")
alphabet_counts = {}
for char in string.upper():
if char.isalpha():
alphabet_counts[char] = alphabet_counts.get(char, 0) + 1
print("Alphabet counts:")
for alphabet in sorted(alphabet_counts.keys()):
count = alphabet_counts[alphabet]
print(f"{count}{alphabet}")
# Method 2: Using collections.Counter
from collections import Counter
string = input("Enter a string: ")
alphabet_counts = Counter(char.upper() for char in string if char.isalpha())
print("Alphabet counts:")
for alphabet in sorted(alphabet_counts.keys()):
count = alphabet_counts[alphabet]
print(f"{count}{alphabet}")
# Method 3: Using list comprehension
string = input("Enter a string: ")
alphabets = [char.upper() for char in string if char.isalpha()]
unique_alphabets = sorted(set(alphabets))
print("Alphabet counts:")
for alphabet in unique_alphabets:
count = alphabets.count(alphabet)
print(f"{count}{alphabet}")
Sample Output:
Enter a string: ABaBCbGc Alphabet counts: 2A 3B 2C 1G
6. Count Unique Words Using Sets
# Method 1: Basic approach
sentence = input("Enter a sentence: ")
words = sentence.split()
unique_words = set(words)
print(f"Total words: {len(words)}")
print(f"Unique words: {len(unique_words)}")
print("Unique words:", sorted(unique_words))
# Method 2: Case insensitive unique words
sentence = input("Enter a sentence: ")
words = sentence.lower().split()
unique_words = set(words)
print(f"Total words: {len(words)}")
print(f"Unique words: {len(unique_words)}")
print("Unique words:", sorted(unique_words))
# Method 3: Remove punctuation and count
import string
sentence = input("Enter a sentence: ")
# Remove punctuation
translator = str.maketrans('', '', string.punctuation)
clean_sentence = sentence.translate(translator)
words = clean_sentence.lower().split()
unique_words = set(words)
print(f"Total words: {len(words)}")
print(f"Unique words: {len(unique_words)}")
print("Unique words:", sorted(unique_words))
Sample Output:
Enter a sentence: The quick brown fox jumps over the lazy dog Total words: 9 Unique words: 8 Unique words: ['brown', 'dog', 'fox', 'jumps', 'lazy', 'over', 'quick', 'the']
7. Set Operations with Fruits
# Create two sets of fruits
n = int(input("Enter number of fruits for each set: "))
print("Enter fruits for set 1:")
s1 = set()
for i in range(n):
fruit = input(f"Enter fruit {i+1}: ")
s1.add(fruit)
print("\nEnter fruits for set 2:")
s2 = set()
for i in range(n):
fruit = input(f"Enter fruit {i+1}: ")
s2.add(fruit)
print(f"\nSet 1: {s1}")
print(f"Set 2: {s2}")
# a) Fruits which are in both sets s1 and s2 (Intersection)
common_fruits = s1 & s2
print(f"\nFruits in both sets: {common_fruits}")
# b) Fruits only in s1 but not in s2 (Difference)
only_s1 = s1 - s2
print(f"Fruits only in set 1: {only_s1}")
# c) Count of all fruits from s1 and s2 (Union)
all_fruits = s1 | s2
print(f"All unique fruits: {all_fruits}")
print(f"Count of all unique fruits: {len(all_fruits)}")
# Additional operations
print(f"\nFruits only in set 2: {s2 - s1}")
print(f"Symmetric difference (fruits in exactly one set): {s1 ^ s2}")
Sample Output:
Enter number of fruits for each set: 3
Enter fruits for set 1:
Enter fruit 1: apple
Enter fruit 2: banana
Enter fruit 3: orange
Enter fruits for set 2:
Enter fruit 1: banana
Enter fruit 2: grape
Enter fruit 3: orange
Set 1: {'orange', 'banana', 'apple'}
Set 2: {'orange', 'grape', 'banana'}
Fruits in both sets: {'orange', 'banana'}
Fruits only in set 1: {'apple'}
All unique fruits: {'orange', 'grape', 'banana', 'apple'}
Count of all unique fruits: 4
8. Various Set Operations
# Define the sets
S1 = {'Red', 'yellow', 'orange', 'blue'}
S2 = {'violet', 'blue', 'purple'}
print(f"Set S1: {S1}")
print(f"Set S2: {S2}")
# Union (All elements from both sets)
union_set = S1 | S1
print(f"\nUnion (S1 ∪ S2): {union_set}")
# Intersection (Common elements)
intersection_set = S1 & S2
print(f"Intersection (S1 ∩ S2): {intersection_set}")
# Difference (Elements in S1 but not in S2)
difference_set = S1 - S2
print(f"Difference (S1 - S2): {difference_set}")
# Difference (Elements in S2 but not in S1)
difference_set2 = S2 - S1
print(f"Difference (S2 - S1): {difference_set2}")
# Symmetric Difference (Elements in exactly one set)
symmetric_diff = S1 ^ S2
print(f"Symmetric Difference: {symmetric_diff}")
# Check if one set is subset of another
print(f"\nIs S1 subset of S2? {S1.issubset(S2)}")
print(f"Is S2 subset of S1? {S2.issubset(S1)}")
# Check if one set is superset of another
print(f"Is S1 superset of S2? {S1.issuperset(S2)}")
print(f"Is S2 superset of S1? {S2.issuperset(S1)}")
# Check if sets are disjoint
print(f"Are S1 and S2 disjoint? {S1.isdisjoint(S2)}")
# Add and remove elements
S1.add('green')
print(f"\nS1 after adding 'green': {S1}")
S2.remove('violet')
print(f"S2 after removing 'violet': {S2}")
# Clear a set
S3 = S1.copy()
S3.clear()
print(f"Copied set after clearing: {S3}")
Sample Output:
Set S1: {'orange', 'blue', 'Red', 'yellow'}
Set S2: {'blue', 'violet', 'purple'}
Union (S1 ∪ S2): {'orange', 'blue', 'Red', 'violet', 'yellow', 'purple'}
Intersection (S1 ∩ S2): {'blue'}
Difference (S1 - S2): {'orange', 'Red', 'yellow'}
Difference (S2 - S1): {'violet', 'purple'}
Symmetric Difference: {'orange', 'Red', 'violet', 'yellow', 'purple'}
Is S1 subset of S2? False
Is S2 subset of S1? False
Is S1 superset of S2? False
Is S2 superset of S1? False
Are S1 and S2 disjoint? False
S1 after adding 'green': {'orange', 'blue', 'Red', 'green', 'yellow'}
S2 after removing 'violet': {'blue', 'purple'}
Copied set after clearing: set()